# schedules/views.py
from rest_framework import generics, permissions, status,serializers  
from rest_framework.response import Response
from rest_framework.views import APIView
from django.utils import timezone
from datetime import time, timedelta
from .models import TimeSlot
from .serializers import (
    TimeSlotSerializer,
    TimeSlotUpdateSerializer,
    BatchTimeSlotSerializer
)
from apps.chefs.models import DjChef
from apps.orders.models import Order
from django.utils.translation import gettext_lazy as _

class AvailableTimeSlotsView(APIView):
    """
    动态档期视图（含未来所有档期）：
    - ≤11:00：今日午餐+晚餐 + 今日之后所有档期
    - 11:00~18:00：今日晚餐 + 今日之后所有档期
    - >18:00：次日及以后所有档期
    """
    def get(self, request, chef_id):
        try:
            # 1. 基础验证与时间获取
            if not isinstance(chef_id, int):
                return Response(
                    {'error': '无效的厨师ID'}, 
                    status=status.HTTP_400_BAD_REQUEST
                )
            
            now = timezone.now()
            today = now.date()
            current_time = now.time()
            print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")

            # 2. 定义时间临界点
            time_11 = time(11, 0)
            time_18 = time(18, 0)
            
            # 3. 构建基础查询（厨师ID过滤）
            base_query = TimeSlot.objects.filter(chef_id=chef_id)
            
            # 4. 分场景筛选今日有效时段 + 未来所有档期
            if current_time <= time_11:
                # 场景1：≤11:00 → 今日(lunch+dinner) + 今日之后所有
                today_slots = base_query.filter(
                    date=today,
                    period__in=['lunch', 'dinner']
                )
                future_slots = base_query.filter(date__gt=today)  # 今日之后（不含今日）
                print("筛选规则：今日(午餐+晚餐) + 未来所有档期")
                
            elif time_11 < current_time <= time_18:
                # 场景2：11:00~18:00 → 今日(dinner) + 今日之后所有
                today_slots = base_query.filter(
                    date=today,
                    period='dinner'
                )
                future_slots = base_query.filter(date__gt=today)
                print("筛选规则：今日(仅晚餐) + 未来所有档期")
                
            else:
                # 场景3：>18:00 → 次日及以后所有（不含今日）
                today_slots = base_query.none()  # 今日无有效时段
                future_slots = base_query.filter(date__gt=today)  # 今日之后（含次日）
                print("筛选规则：次日及以后所有档期")

            # 5. 合并结果并去重排序（按日期→时段）
            valid_slots = (today_slots | future_slots).distinct().order_by('date', 'period')

            # 6. 处理响应数据
            slots_data = []
            for slot in valid_slots:
                slots_data.append({
                    'id': slot.id,
                    'date': slot.date,
                    'period': slot.period,
                    'status': slot.status,
                    'display_date': slot.date.strftime("%Y-%m-%d"),
                    'display_weekday': slot.date.strftime("%a"),
                    'display_period': dict(TimeSlot.PERIOD_CHOICES).get(slot.period, slot.period),
                    'is_today': slot.date == today,
                    'is_future': slot.date > today
                })
            
            print(f"符合条件的档期数量: {len(slots_data)}")
            return Response(slots_data)

        except Exception as e:
            print(f"获取档期失败: {str(e)}")
            return Response(
                {'error': f'服务器错误: {str(e)}'}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )


class ChefTimeSlotView(generics.ListCreateAPIView):
    """
    获取/创建厨师档期
    GET: 获取厨师档期列表
    POST: 创建新档期（自动处理冲突）
    """
    serializer_class = TimeSlotSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]

    def get_queryset(self):
        chef_id = self.kwargs['chef_id']
        return TimeSlot.objects.filter(
            chef_id=chef_id,
            date__gte=timezone.now().date()
        ).select_related('chef')

    def create(self, request, *args, **kwargs):
        chef = DjChef.objects.get(id=kwargs['chef_id'])
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        # 自动处理唯一约束
        time_slot, created = TimeSlot.objects.get_or_create(
            chef=chef,
            date=serializer.validated_data['date'],
            period=serializer.validated_data['period'],
            defaults={'status': 'available'}
        )
        
        if not created:
            time_slot.status = serializer.validated_data.get('status', 'available')
            time_slot.save()
        
        headers = self.get_success_headers(serializer.data)
        return Response(
            TimeSlotSerializer(time_slot).data,
            status=status.HTTP_201_CREATED if created else status.HTTP_200_OK,
            headers=headers
        )

class TimeSlotBatchCreateView(generics.CreateAPIView):
    """
    批量生成档期
    POST: 为指定日期范围生成档期
    """
    serializer_class = BatchTimeSlotSerializer
    permission_classes = [permissions.IsAuthenticated]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        
        chef_id = kwargs['chef_id']
        created_slots = []
        current_date = serializer.validated_data['start_date']
        
        while current_date <= serializer.validated_data['end_date']:
            for period in serializer.validated_data['periods']:
                slot, _ = TimeSlot.objects.get_or_create(
                    chef_id=chef_id,
                    date=current_date,
                    period=period,
                    defaults={'status': 'available'}
                )
                created_slots.append(slot)
            current_date += timedelta(days=1)
        
        return Response({
            'count': len(created_slots),
            'results': TimeSlotSerializer(created_slots, many=True).data
        }, status=status.HTTP_201_CREATED)

class TimeSlotRangeView(generics.ListAPIView):
    """
    按条件查询档期
    GET: 支持日期范围、状态、时段等多条件筛选
    """
    serializer_class = TimeSlotSerializer

    def get_queryset(self):
        queryset = TimeSlot.objects.filter(
            date__gte=timezone.now().date()
        ).select_related('chef')
        
        # 状态筛选
        if status := self.request.query_params.get('status'):
            queryset = queryset.filter(status=status)
            
        # 日期范围筛选
        if start_date := self.request.query_params.get('start_date'):
            queryset = queryset.filter(date__gte=start_date)
        if end_date := self.request.query_params.get('end_date'):
            queryset = queryset.filter(date__lte=end_date)
            
        # 时段筛选
        if periods := self.request.query_params.getlist('period'):
            queryset = queryset.filter(period__in=periods)
            
        return queryset

class TimeSlotUpdateView(generics.RetrieveUpdateDestroyAPIView):
    """
    档期详情管理
    GET: 获取详情
    PATCH: 部分更新（主要用于状态变更）
    DELETE: 删除档期
    """
    queryset = TimeSlot.objects.all()
    serializer_class = TimeSlotUpdateSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_serializer_class(self):
        if self.request.method == 'GET':
            return TimeSlotSerializer
        return TimeSlotUpdateSerializer

    def perform_update(self, serializer):
        instance = serializer.save()
        self._check_booking_status(instance)

    def _check_booking_status(self, time_slot):
        """状态变更为booked时验证订单冲突"""
        if time_slot.status == 'booked':
            if Order.objects.filter(
                chef=time_slot.chef,
                service_date=time_slot.date,
                service_period=time_slot.period,
                status__in=['confirmed', 'serving']
            ).exists():
                raise serializers.ValidationError(_('该时段已有进行中的订单'))